<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 使用el-form组件包裹并设置校验规则 -->
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
        <div class="login-top">
          <img src="@/assets/imgs/login/logo.png" alt="登录logo" />
        </div>

        <!-- 账号输入框 -->
        <el-form-item prop="account" class="form-item">
          <el-input v-model="loginForm.account" placeholder="用户名" :prefix-icon="User" />
        </el-form-item>

        <!-- 密码输入框和忘记密码 -->
        <div class="password-wrapper">
          <el-form-item prop="password" class="form-item">
            <el-input
              v-model="loginForm.password"
              placeholder="密码"
              :prefix-icon="Lock"
              type="password"
            />
          </el-form-item>
          <span @click="forgetPsd" class="forget-psd">忘记密码</span>
        </div>

        <!-- 角色选择 -->
        <el-form-item prop="role" class="form-item">
          <el-select v-model="loginForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="普通用户" value="user"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item class="form-item">
          <button
            class="btn-base login-btn"
            type="primary"
            @click="handleLogin"
            :disabled="isLoading"
          >
            <template v-if="isLoading">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                class="loading-spinner"
              >
                <line x1="12" y1="2" x2="12" y2="6"></line>
                <line x1="12" y1="18" x2="12" y2="22"></line>
                <line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line>
                <line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line>
                <line x1="2" y1="12" x2="6" y2="12"></line>
                <line x1="18" y1="12" x2="22" y2="12"></line>
                <line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line>
                <line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line>
              </svg>
              登录中...
            </template>
            <template v-else>登录</template>
          </button>
        </el-form-item>

        <!-- 权限演示区域 -->
        <div v-permission="'admin'" style="margin-top: 20px; padding: 10px; background-color: #f0f9ff; border-radius: 4px;">
          <p style="color: #409eff; margin: 0;">
            <i class="el-icon-user"></i>
            管理员专属提示：这是仅管理员可见的内容
          </p>
        </div>

        <div v-permission="['admin', 'user']" style="margin-top: 10px; padding: 10px; background-color: #f0f9ff; border-radius: 4px;">
          <p style="color: #67c23a; margin: 0;">
            <i class="el-icon-info"></i>
            所有用户可见提示：这是所有登录用户都可见的内容
          </p>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// 引入Pinia的用户存储
import { useUserStore } from '@/stores/user'
// 引入登录API
import { login } from '@/api/auth'

// 表单数据
const loginForm = reactive({
  account: '',
  password: '',
  role: 'admin', // 默认选择管理员角色
})

// 表单引用
const loginFormRef = ref(null)
// 路由实例
const router = useRouter()
// 用户存储实例
const userStore = useUserStore()
// 登录加载状态
const isLoading = ref(false)

// 校验规则
const loginRules = {
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '用户名长度在 3 到 15 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' },
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
}

const forgetPsd = () => {
  console.log('忘记密码')
}

// 登录处理函数
const handleLogin = async () => {
  try {
    // 显示加载状态
    isLoading.value = true

    // 表单验证
    const valid = await loginFormRef.value.validate()

    if (valid) {
      console.log('开始登录请求:', {
        account: loginForm.account,
        role: loginForm.role
      })

      // 调用后端登录接口
      const res = await login({
        account: loginForm.account,
        password: loginForm.password,
        role: loginForm.role
      })

      console.log('登录响应:', res)

      if (res.code === 200) {
        // 登录成功，保存用户信息到Pinia
        userStore.setUserInfo(res.data)

        // 保存token到localStorage
        localStorage.setItem('token', res.data.token)

        ElMessage.success('登录成功，正在跳转...')
        console.log('登录成功，用户信息已保存到Pinia:', userStore)

        // 跳转到首页
        setTimeout(() => {
          router.push('/')
        }, 500)
      } else {
        // 登录失败
        ElMessage.error(res.message || '登录失败')
      }
    }
  } catch (error) {
    // 网络错误或其他异常
    console.error('登录异常:', error)

    // 提供更友好的错误提示
    if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请检查网络连接')
    } else if (!error.response) {
      ElMessage.error('网络连接失败，请检查后端服务是否启动')
    } else {
      ElMessage.error('登录异常，请稍后重试')
    }
  } finally {
    // 无论成功失败，都关闭加载状态
    isLoading.value = false
  }
}
</script>

<style scoped lang="scss">
.login-container {
  height: 100vh;
  background-color: rgb(251, 253, 251);
  background: url('../../assets/imgs/login/bg.png') no-repeat center center;
  background-size: cover;
  background-attachment: fixed;

  .login-box {
    position: absolute;
    left: 12%;
    top: 25%;
    width: 320px;
    padding: 30px 20px;
    background-color: rgba(254, 254, 249, 0.2);
    border-radius: 10px;
    box-shadow: 5px 5px 5px rgba(233, 227, 227, 0.3);

    .login-form {
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;

      .login-top {
        margin-bottom: 25px;
        text-align: center;
        img {
          width: 140px;
          height: 50px;
        }
      }

      // 统一所有表单项的宽度
      .form-item {
        width: 240px;
        margin-bottom: 12px;
      }

      :deep(.el-input) {
        width: 100%; // 输入框占满父容器宽度
      }

      .password-wrapper {
        width: 240px; // 与其他元素保持相同宽度
      }

      .forget-psd {
        display: block;
        text-align: right;
        margin-top: 6px;
        margin-bottom: 8px;
        cursor: pointer;
        font-size: 12px;
        color: rgb(213, 218, 224);
        transition: color 0.2s;

        &:hover {
          color: #71777d;
        }
      }



      .login-btn {
        width: 100%;
        height: 37px;
        padding: 10px 0;
        &:hover {
          background-color: #0080ff;
        }
        &:disabled {
          opacity: 0.7;
          cursor: not-allowed;
        }
      }

      .loading-spinner {
        margin-right: 6px;
        animation: spin 1s linear infinite;
      }
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
